<?php

namespace app\company\controller;

use app\merchant\model\ExpenseRecordModel;
use app\merchant\model\MerchantModel;
use app\pilot\model\BalanceRecordModel;
use app\pilot\model\PilotModel;
use app\task\model\OrderModel;
use app\task\model\TaskModel;
use think\admin\Controller;
use think\admin\service\AdminService;
use think\Exception;
use think\facade\Db;

/**
 * 订单接单管理
 * @class Task
 * @package app\task\controller
 */
class Order extends Controller
{
    /**
     * 订单接单列表
     * @auth true
     * @menu true
     */
    public function index()
    {
        $merchant = $this->app->session->get('merchant');
        if (empty($merchant)) $this->error('没有权限');
        $this->title = '订单接单列表';
        $this->status_dict = OrderModel::STATUS_DICT;
        OrderModel::mQuery()->alias('o')->where('o.is_deleted', 0)
            ->with(['task'=>['category', 'merchant', 'transport'], 'pilot'])
            ->field('o.*')
            ->join('task t', 'o.task_id=t.id', 'left')
            ->join('pilot p', 'o.pilot_id=p.id', 'left')
            ->join('task_transport tr', 'tr.task_id=t.id', 'left')
            ->where('t.merchant_id', $merchant['id'])
            ->like('p.nickname#nickname,p.realname#realname,t.name#name,tr.type#transport_type,tr.scene#transport_scene')
            ->equal('o.status#status,o.task_id#task_id')
            ->dateBetween('o.create_at#create_at,t.exec_at#exec_at')
            ->order('o.id desc')
            ->layTable();
    }

    /**
     * 列表数据处理
     * @param array $data
     */
    protected function _index_page_filter(array &$data)
    {
        foreach ($data as &$vo){
            if(isset($vo['status'])) $vo['status_text'] = OrderModel::STATUS_DICT[$vo['status']] ?? '';
        }
    }

    /**
     * 订单任务详情
     * @auth true
     */
    public function detail()
    {
        $this->vo = OrderModel::with(['task'=>['category', 'merchant', 'transport'], 'pilot'])->where('id', $this->request->get('id'))->find();
        $this->fetch();
    }


    /**
     * 添加订单接单
     * @auth true
     */
//    public function add()
//    {
////        $this->_applyFormToken();
//        OrderModel::mForm('form');
//    }

    /**
     * 添加订单接单
     * @auth true
     */
//    public function edit()
//    {
////        $this->_applyFormToken();
//        OrderModel::mForm('form');
//    }

    /**
     * 表单数据处理
     * @param array $vo
     */
    protected function _form_filter(array &$vo)
    {
        if ($this->request->isGet()) {

        }
    }

    /**
     * 修改接单状态
     * @auth true
     */
//    public function state()
//    {
//        OrderModel::mSave($this->_vali([
//            'status.in:0,1'  => '状态值范围异常！',
//            'status.require' => '状态值不能为空！',
//        ]));
//    }

    /**
     * 删除订单任务分接单
     * @auth true
     */
//    public function remove()
//    {
//        OrderModel::mDelete();
//    }

    /**
     * 订单任务申请通过
     * @auth true
     */
    public function apply_review()
    {
        Db::startTrans();
        try {
            $merchant = $this->app->session->get('merchant');
            if (empty($merchant)) $this->error('没有权限');
            $id = $this->request->post('id');
            $order = OrderModel::with('task')->where('is_deleted', 0)->where('id', $id)->lock(true)->find();
            if (empty($order)) $this->error('订单接单申请不存在');
            if ($order->task->merchant_id != $merchant['id']) $this->error('订单接单申请不存在');
            if ($order->status != OrderModel::STATUS__APPLYING) $this->error('申请中的订单任务才能审核');
            // 状态改为待完成
            $order->save([
                'status' => OrderModel::STATUS__PENDING_COMPLETION,
                'review_at' => date('Y-m-d H:i:s'),
                'apply_review_admin_id' => AdminService::getUserId()
            ]);
            // 其他订单任务申请同意改为候补中
            $res = Db::name('task_order')->where('is_deleted', 0)
                ->where('status', OrderModel::STATUS__APPLYING)
                ->where('task_id', $order->task_id)
                ->where('id', '<>', $id)
                ->update(['status'=>OrderModel::STATUS__STANDBY]);
            if ($res === false) $this->error('订单任务申请审核失败');
            // 更新任务状态
            $task = TaskModel::where(['is_deleted'=>0, 'status'=>1])
                ->where('task_status', TaskModel::TASK_STATUS__PENDING_ACCEPTANCE)
                ->whereTime('exec_at', '>', date('Y-m-d H:i:s'))
                ->where('id', $order->task_id)
                ->lock(true)
                ->find();
            if (empty($task)) $this->error('订单任务不存在');
            $task->order_id = $order->id;
            $task->task_status = TaskModel::TASK_STATUS__PENDING_COMPLETION;
            $task->save();
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }

    /**
     * 取消订单任务订单
     * @auth true
     */
    public function cancel()
    {
        if ($this->request->isGet()){
            $this->vo = OrderModel::with(['task'=>['category', 'merchant', 'transport'], 'pilot'])->where('id', $this->request->get('id'))->find();
            $this->fetch();
        }else{
            $merchant = $this->app->session->get('merchant');
            if (empty($merchant)) $this->error('没有权限');
            $id = $this->request->post('id');
            $cancel_reason = $this->request->post('cancel_reason');
            $order = OrderModel::with('task')->where('is_deleted', 0)->where('id', $id)->lock(true)->find();
            if (empty($order)) $this->error('订单任务订单不存在');
            if ($order->task->merchant_id != $merchant['id']) $this->error('订单接单申请不存在');
            if (!in_array($order->status, [OrderModel::STATUS__APPLYING, OrderModel::STATUS__PENDING_COMPLETION, OrderModel::STATUS__STANDBY])) $this->error('申请中、候补中、待完成的订单任务才能取消');
//            if (empty($cancel_reason)) $this->error('请填写取消的原因');
            OrderModel::mSave([
                'id' => $id,
                'status' => OrderModel::STATUS__CANCELED,
                'cancel_reason' => $cancel_reason,
            ]);
        }
    }

    /**
     * 订单任务完成
     * @auth true
     */
    public function order_review()
    {
        $merchant = $this->app->session->get('merchant');
        if (empty($merchant)) $this->error('没有权限');

        $id = $this->request->post('id', 0);
//        $review_status = $this->request->post('review_status', 0);
        $review_status = 1;
        $review_reason = $this->request->post('review_reason', '');
        // 当前只允许通过审核
        if ($review_status != 1) $this->error('审核状态不正确');
        if (empty($id)) $this->error('ID不能为空');
        Db::startTrans();
        try {
            $task_order = OrderModel::where(['is_deleted'=>0])
                ->where('status', OrderModel::STATUS__PENDING_REVIEW)
                ->where('id', $id)
                ->lock(true)
                ->find();
            if (empty($task_order)) $this->error('订单任务订单不存在');
            $task = TaskModel::where(['is_deleted'=>0, 'status'=>1])
                ->where('merchant_id', $merchant['id'])
                ->where('task_status', TaskModel::TASK_STATUS__PENDING_COMPLETION)
                ->where('id', $task_order->task_id)
                ->lock(true)
                ->find();
            if (empty($task)) $this->error('订单任务不存在');
            // 变更任务状态
            $task->task_status = TaskModel::TASK_STATUS__COMPLETED;
            $task->save();
            $task_order->status = OrderModel::STATUS__COMPLETED;
            $task_order->review_at = date('Y-m-d H:i:s');
            $task_order->update_at = date('Y-m-d H:i:s');
            $task_order->save();
            // 商户-增加支出金额和支出记录
            $merchant = MerchantModel::where('id', $task->merchant_id)
                ->lock(true)
                ->find();
            ExpenseRecordModel::create([
                'merchant_id' => $merchant->id,
                'type' => 1,
                'amount' => $task->money,
                'before' => $merchant->expense,
                'after' => $merchant->expense + $task->money,
                'remark' => '',
                'task_order_id' => $task_order->id,
            ]);
            $merchant->expense += $task->money;
            $merchant->save();
            // 飞手-增加余额和余额记录
            $pilot = PilotModel::where('id', $task_order->pilot_id)
                ->lock(true)
                ->find();
            BalanceRecordModel::create([
                'pilot_id' => $pilot->id,
                'type' => 1,
                'amount' => $task_order->money,
                'before' => $pilot->balance,
                'after' => $pilot->balance + $task_order->money,
                'remark' => '',
                'task_order_id' => $task_order->id,
            ]);
            $pilot->balance += $task_order->money;
            $pilot->save();
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }
}
